# -*- coding: utf-8 -*-

import tornado.ioloop
import tornado.web
import os
from ObjJsonEncoder import ObjEncoder
from Video import Video
import sys
import json

myencode = "utf-8"
reload(sys)
sys.setdefaultencoding(myencode)
dir_path = "F:\\video"
ip = 'http://192.168.1.101'
port = 8888

def list_video(path):
    jsonString = []

    for d in os.walk(path):
        for f in d[2]: #filename
            f = f.decode('gbk')
            title = f
            video_url = ip+':'+str(port)+ os.path.join(d[0], f).replace(dir_path, "/static").replace("\\", "/") #file path
            video = dict(title=title, url=video_url)
            jsonString.append(video)

    return jsonString

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        real_path = self.get_argument('path', '')
        reponse = list_video(dir_path)

        #list to json
        try:
            result = json.dumps(reponse)
            # result = ObjEncoder().encode(reponse)
            result = "{"+"\"data\":"+result+"}"
            self.write(result)
        except TypeError, err:
            print err

class VideoHandler(tornado.web.RequestHandler):
    def get(self):
        #获取到文件参数
        file_name = self.get_argument('id','')
        self.write("请求播放视频"+file_name)

#定义静态文件库 只是支持一个文件夹
settings = {
    "static_path": "F:\\video"
}

handlers = [
    (r"/video", MainHandler),
    (r"/video/play", VideoHandler),
]

application = tornado.web.Application(handlers, **settings)

if __name__ == "__main__":
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()




